package implementation.sort;

import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;
import implementation.sort.AbstractSorter;

import java.util.Comparator;
import java.util.List;


public class HeapSortTernary extends AbstractSorter {

    public HeapSortTernary() {
        super(SorterType.HEAP_TERNARY);
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        sort(tComparator, ts, 0, ts.size() - 1);
    }

    private <T> void sort(Comparator<T> tComparator, List<T> ts, int l, int n) {
        for (int i = (n - 1) / 3; i >= l; i--) {
            sink(tComparator, ts, i, n);
        }
        while (n > l) {
            swap(ts, l, n--);
            sink(tComparator, ts, l, n);
        }
    }

    private <T> void sink(Comparator<T> tComparator, List<T> ts, int k, int n) {
        while ((((k + 1) * 3) - 2) <= n) {
            int j = ((k + 1) * 3) - 2;
            int p = ((k + 1) * 3);

            if (j < n && !greater(tComparator, ts, j, j + 1)) {
                j++;
            }
            if (p <= n && !greater(tComparator,ts, j, p)) {
                j = p;
            }
            if (greater(tComparator, ts, k, j)) {
                break;
            }
            swap(ts, k, j);
            k = j;
        }
    }
}
